#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/27 13:09
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : email_config.py
# @Software: PyCharm
# @Desc    :
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File    : email_config.py
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.generics import GenericAPIView

from common.utils.pagination import EnhancedPageNumberPagination
from common.utils.rsp import success_response
from semail.filters.filter_email_config import EmailConfigFilter
from semail.models import EmailConfig
from semail.sers.ser_email_config import EmailConfigSerializer


class EmailConfigListCreateView(GenericAPIView):
    """
    EmailConfig列表查询 + 新增接口
    - GET: 分页查询邮箱配置列表（支持过滤、排序）
    - POST: 新增邮箱配置（自动校验默认配置唯一性）
    """
    queryset = EmailConfig.objects.filter(is_delete=0, pt_flag=0).all()
    serializer_class = EmailConfigSerializer
    pagination_class = EnhancedPageNumberPagination

    # 过滤与排序配置
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = EmailConfigFilter
    ordering_fields = ["create_time", "name", "sort_num", "is_default"]
    # ordering = ["-is_default", "-create_time"]  # 默认：默认配置在前，按创建时间倒序

    def get(self, request, *args, **kwargs):
        """GET请求：分页查询配置列表"""
        filtered_qs = self.filter_queryset(self.get_queryset())
        page_qs = self.paginate_queryset(filtered_qs)
        serializer = self.get_serializer(page_qs, many=True)
        paginated_data = self.paginator.get_paginated_response(serializer.data).data

        return success_response(
            data=paginated_data,
            message="邮箱配置列表查询成功"
        )

    def post(self, request, *args, **kwargs):
        """POST请求：新增邮箱配置"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return success_response(
            data=serializer.data,
            message=f"邮箱配置「{serializer.validated_data['name']}」创建成功"
        )


class EmailConfigRetrieveUpdateDestroyView(GenericAPIView):
    """
    EmailConfig单条操作接口
    - GET: 查询单个配置详情
    - PUT: 全量更新配置
    - PATCH: 部分更新配置
    - DELETE: 逻辑删除配置
    """
    queryset = EmailConfig.objects.all()
    serializer_class = EmailConfigSerializer
    lookup_field = "pk"

    def get_object(self):
        """只允许操作「未删除+非压测」的有效配置"""
        instance = super().get_object()
        if instance.is_delete == 1 or instance.pt_flag == 1:
            raise ValueError("当前邮箱配置不存在或已被删除，无法操作！")
        return instance

    def get(self, request, *args, **kwargs):
        """GET请求：查询单个配置详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(data=serializer.data, message="邮箱配置详情查询成功")

    def put(self, request, *args, **kwargs):
        """PUT请求：全量更新配置"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=False)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return success_response(
            data=serializer.data,
            message=f"邮箱配置「{instance.name}」全量更新成功"
        )

    def patch(self, request, *args, **kwargs):
        """PATCH请求：部分更新配置"""
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return success_response(
            data=serializer.data,
            message=f"邮箱配置「{instance.name}」部分更新成功"
        )

    def delete(self, request, *args, **kwargs):
        """DELETE请求：逻辑删除配置"""
        instance = self.get_object()
        config_name = instance.name
        instance.is_delete = 1
        instance.save()

        return success_response(
            data=None,
            message=f"邮箱配置「{config_name}」已成功删除（逻辑删除）"
        )
